package com.ebt.m.proposal_v2.ui;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ebt.m.R;
import com.ebt.m.commons.buscomponent.thirtylogin.model.ShareListener;
import com.ebt.m.commons.utils.Logger;
import com.ebt.m.customer.util.PhoneUtil;
import com.ebt.m.proposal_v2.base.Constant;
import com.ebt.m.proposal_v2.bean.ArgProposalDetail;
import com.ebt.m.proposal_v2.bean.ShareBody;
import com.ebt.m.proposal_v2.dao.file.DiskUtils;
import com.ebt.m.proposal_v2.helper.NativeAPI;
import com.ebt.m.proposal_v2.helper.ThemeHelper;
import com.ebt.m.proposal_v2.helper.WebViewCallback;
import com.ebt.m.proposal_v2.helper.WebViewSetter;
import com.ebt.m.proposal_v2.mvp.base.MVPCompatActivity;
import com.ebt.m.proposal_v2.mvp.contract.ProposalDetailContract;
import com.ebt.m.proposal_v2.mvp.presenter.ProposalDetailPresenter;
import com.ebt.m.proposal_v2.utils.DataUtils;
import com.ebt.m.proposal_v2.utils.RxUtils;
import com.ebt.m.proposal_v2.utils.ViewUtils;
import com.ebt.m.share.ShareDialog;
import com.ebt.m.share.ShareEvent;
import com.ebt.m.utils.FileDownloader;
import com.ebt.m.utils.UIHelper;
import com.tencent.tauth.Tencent;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 计划书预览
 *
 * @author archer.qi
 *         Created on 2017/5/12.
 */
public class ProposalDetailActivity extends MVPCompatActivity<ProposalDetailPresenter>
        implements ProposalDetailContract.View {
    public static final String ArgProposalDetail = "ArgProposalDetail";
    @BindView(R.id.toolbar)
    Toolbar mTopBar;
    @BindView(R.id.icon_back)
    ImageButton icon_back;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.proposal_detail_bottom)
    LinearLayout mBottomBar;
    @BindView(R.id.proposal_detail_voice)
    RelativeLayout mVoiceView;
    @BindView(R.id.proposal_detail_voice_text)
    TextView mVoiceText;
    @BindView(R.id.proposal_detail_send)
    Button mSendProposalView;
    @BindView(R.id.proposal_detail_webView)
    WebView mWebView;
    @BindView(R.id.loading)
    ProgressBar mProgressBar;
    protected View netError;
    protected View serverError;

    /* WebView配置*/
    private WebViewSetter mWebSetter;
    /* WebView交互*/
    private WebViewCallback mWebCallback;
    /* 传递参数*/
    private ArgProposalDetail mArgument;
    private Drawable drawableLeftGreen, drawableLeft;

    @Override
    protected ProposalDetailPresenter createPresenter() {
        return new ProposalDetailPresenter(getApplicationContext(), this);
    }

    @Override
    protected int setContentResource() {
        return R.layout.activity_proposal_detail;
    }

    @Override
    protected void onActivityCreate() {
        initArguments();
        checkPreviewUrl();
        initBarView();
        initWebView();
        initAudioResource();
    }

    @Override
    protected void onActivityDestroy() {
        if (mWebSetter != null) {
            mWebSetter.destroyWebView();
        }
        if (mWebView != null) {
            mWebView = null;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mWebSetter == null) {
                return super.onKeyDown(keyCode, event);
            }
            boolean canGoBack = mWebSetter.performOnBackPress();
            if (canGoBack) {
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void initBarView() {
        tvTitle.setText(mArgument == null ? "" : checkNull(mArgument.proposalName));
        /**
         * 发送计划书或查看隐藏底部栏
         */
        if (mArgument.isProposalPosted) {
            initViewByDetailMode();
        } else {
            initViewByPreviewMode();
        }
        RxUtils.click(mSendProposalView, view -> mPresenter.performSendProposal());
        RxUtils.click(mVoiceView, view -> mPresenter.performVoice());
        RxUtils.click(icon_back, view -> finish());
    }

    private String generateWebViewUrl() {
        String originalUrl = mArgument.previewUrl;
        /**
         * isShowShareBtn分享标识
         * 当Native存在分享键，则提示HTML5不显示；反之亦然
         */
        if (mArgument.isProposalPosted) {
            if (mArgument.checkShare()) {
                originalUrl = DataUtils.addUrlParam(originalUrl, "isShowShareBtn=1");
            } else {
                originalUrl = DataUtils.addUrlParam(originalUrl, "isShowShareBtn=0");
            }
        } else {
            originalUrl = DataUtils.addUrlParam(originalUrl, "isShowShareBtn=0");
        }

        String url = ViewUtils.processUrl(originalUrl);
        Logger.i("->预览页面Url = " + url);
        return url;
    }

    @Override
    public void initWebView() {
        this.netError = findViewById(R.id.no_net_container);
        this.serverError = findViewById(R.id.net_slow_container);
        showProgress("正在加载页面");
        this.netError.findViewById(R.id.load_refresh_net).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideFailView();
                mWebView.reload();
            }
        });
        this.serverError.findViewById(R.id.load_refresh).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideFailView();
                mWebView.reload();
            }
        });

        mWebSetter = new WebViewSetter()
                .with(mWebView)
                .supportJavaScript()
                .allowFileAccess()
                .encodingTextByUTF8()
                .javaScriptCanOpenWindow()
                .loadImagesAuto()
                .showNetworkImage()
                .supportMixContentMode()
                .wrapViewPort()
                .enableDomStorage()
                .loadUrl(generateWebViewUrl());
        mWebCallback = new WebViewCallback()
                .with(mWebView)
                .addNativeInterface(new ProposalDetailNativeAPI(this), Constant.JSCallInstance);

        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress == 100) {
                    mProgressBar.setVisibility(View.GONE);

                } else {
                    if (mProgressBar.getVisibility() == View.GONE)
                        mProgressBar.setVisibility(View.VISIBLE);
                    mProgressBar.setProgress(newProgress);
                }
                if (newProgress >= 100) {
                    cancelProgress();
                }
            }
        });
        mWebView.setWebViewClient(new WebViewClient() {
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                String url = request.getUrl().toString();
                if (url != null && (url.startsWith("http") || url.startsWith("https"))) {
                    view.loadUrl(ViewUtils.processUrl(url));
                    return true;
                }
                if (url.startsWith("tel:")) {
                    PhoneUtil.callPhone(ProposalDetailActivity.this, Uri.parse(url));
                    return true;
                }
                return super.shouldOverrideUrlLoading(view, request);
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                if (error.getPrimaryError() == SslError.SSL_INVALID) {
                    handler.proceed();
                } else {
                    handler.cancel();
                }
            }

            @Override
            // 新版本，只会在Android6及以上调用
            @TargetApi(Build.VERSION_CODES.M)
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError
                    error) {
                super.onReceivedError(view, request, error);
                if (request.isForMainFrame()) {
                    // 在这里显示自定义错误页
                    showFail(error.getErrorCode());
                }
            }

            /**
             * 旧API在新API中也会被调用
             *
             * @param view
             * @param errorCode
             * @param description
             * @param failingUrl
             */
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    return;
                }
                showFail(errorCode);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                /**
                 * Html5页面有header,Native就隐藏
                 */
                if (mArgument.previewUrl.contains("header=true") && netError.getVisibility() != View.VISIBLE && serverError.getVisibility() != View.VISIBLE) {
                    mTopBar.setVisibility(View.GONE);
                } else {
                    mTopBar.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    /**
     * 隐藏错误view
     */
    private void hideFailView() {
        netError.setVisibility(View.GONE);
        serverError.setVisibility(View.GONE);
    }

    protected void showFail(int errorCode) {
        Logger.e("errorCode = " + errorCode);
        mProgressBar.setVisibility(View.GONE);
        if (mWebView.canGoBack()) {
            return;
        }
        int type = 0;//网络不可用
        switch (errorCode) {
            case WebViewClient.ERROR_HOST_LOOKUP://网络不通
                type = 1;
                break;
            case WebViewClient.ERROR_TIMEOUT:// /** Connection timed out */
                type = 2;
                break;
            case WebViewClient.ERROR_CONNECT:///** Failed to connect to the server */
                type = 1;
                break;
            case WebViewClient.ERROR_IO://    /** Failed to read or write to the server */
                type = 2;
                break;
            default://默认加载失败
//                loadFail.setErrorType(EBTErrorView.ErrorType.LOAD_ERROR);
                break;
        }
        showFailView(type);
    }

    /**
     * 显示错误view
     *
     * @param type
     */
    private void showFailView(int type) {
        if (type == 1) {
            mWebView.stopLoading();
            mWebView.clearView();
            Toast.makeText(this, getResources().getString(R.string.network_fail), Toast.LENGTH_SHORT).show();
            netError.setVisibility(View.VISIBLE);
            serverError.setVisibility(View.GONE);
        } else if (type == 2) {
            mWebView.stopLoading();
            mWebView.clearView();
            netError.setVisibility(View.GONE);
            serverError.setVisibility(View.VISIBLE);
        }
        if (netError.getVisibility() == View.VISIBLE || serverError.getVisibility() == View.VISIBLE) {
            if (mTopBar.getVisibility() != View.VISIBLE) {
                mTopBar.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void initAudioResource() {
        setNoAudio(); // 默认无录音
        DiskUtils.deleteFile(Constant.outputTap); // 移除旧录音文件
        if (!mArgument.isNewProposal) { // 不是新建的计划书，需要加载录音文件
            mPresenter.getProposalTap(mArgument.proposalId);
        }
    }

    @Override
    public void setBottomBarShown(boolean shown) {
        mBottomBar.setVisibility(shown ? View.VISIBLE : View.GONE);
    }

    @Override
    public void initViewByDetailMode() {
        // 来自已发送与已查看的计划书
        setBottomBarShown(false);
    }

    @Override
    public void initViewByPreviewMode() {
        // 来自未发送的计划书
        setBottomBarShown(true);
    }

    @Override
    public void showProgress(String msg) {
    }

    @Override
    public void cancelProgress() {
    }

    @Override
    public void initArguments() {
        Bundle mArgs = getIntent().getExtras();
        if (mArgs != null) {
            mArgument = (ArgProposalDetail) mArgs.getSerializable(ArgProposalDetail);
        }
    }

    @Override
    public void setEmptyView(boolean isEmpty) {

    }

    @Override
    public void setNoAudio() {
        mVoiceText.setText("语音");
        mVoiceText.setTextColor(ThemeHelper.getColor(this, R.color.PrimaryContentColor));
        if (drawableLeft == null) {
            drawableLeft = ThemeHelper.getDrawable(this, R.drawable.ic_voice_gray);
            drawableLeft.setBounds(0, 0, 30, 45);
        }
        mVoiceText.setCompoundDrawables(drawableLeft, null, null, null);
    }

    @Override
    public void setAudio(long duration) {
        mVoiceText.setText("语音" + duration + "\"");
        mVoiceText.setTextColor(ThemeHelper.getColor(this, R.color.PrimaryThemeColor));
        if (drawableLeftGreen == null) {
            drawableLeftGreen = ThemeHelper.getDrawable(this, R.drawable.ic_voice_green);
            drawableLeftGreen.setBounds(0, 0, 30, 45);
        }
        mVoiceText.setCompoundDrawables(drawableLeftGreen, null, null, null);
    }

    @Override
    public ArgProposalDetail getArgument() {
        return mArgument;
    }

    @Override
    public void checkPreviewUrl() {
        if (mArgument == null) {
            showToast("您要预览的计划书不存在");
            finish();
            return;
        }
        if (TextUtils.isEmpty(mArgument.proposalId) || TextUtils.isEmpty(mArgument.previewUrl)) {
            showToast("您要预览的计划书不存在");
            finish();
            return;
        }
    }


    boolean isFront;

    @Override
    protected void onStart() {
        super.onStart();
        isFront = true;
    }

    @Override
    protected void onStop() {
        super.onStop();
        isFront = false;
    }

    @Override
    public void openShare(ShareBody body) {

        if (!isFront){
            return;
        }
        List<String> hideList = new ArrayList<>();
        hideList.add(ShareDialog.COPY_LINK);
        new ShareDialog.Builder(this)
                .setShareTitle(body.title)
                .setShareContent(body.content)
                .setShareUrl(body.shareUrl)
                .setShareUrlWeXin(body.shareUrlWeXin)
                .setHidePlatformList(hideList)
                .setShareImagePath(body.shareImagePath)
                .setShareListener(mShareListener)
                .setDialogDismissIfShareSuccess()
                .setBeforeShareListener(() -> mPresenter.sendProposal())
                .create()
                .show();
        /**
         * 改为在点击分享的时候，就发送计划书
         */
    }

    @Override
    public void showToast(String content) {
        UIHelper.makeToast(getApplicationContext(), content);
    }

    @Override
    public FragmentManager getFrgManager() {
        return getSupportFragmentManager();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Tencent.onActivityResultData(requestCode, resultCode, data, mShareListener);
    }

    /**
     * 计划书详情与JS交互类
     */
    public class ProposalDetailNativeAPI extends NativeAPI {

        public ProposalDetailNativeAPI(Context context) {
            super(context);
        }

        @JavascriptInterface
        public void ebtShare() {
            mPresenter.performSendProposal();
        }

        @JavascriptInterface
        public void ebtBack() {
            finish();
        }

        @JavascriptInterface
        public void openWebview(String pdfUrl, String fileName) {
            if (pdfUrl == null || pdfUrl.equalsIgnoreCase("") || pdfUrl.equalsIgnoreCase("undefined")) {
                return;
            }
            FileDownloader fileDownloader = new FileDownloader(ProposalDetailActivity.this, null);
            fileDownloader.downLoadPdf(pdfUrl, fileName);
        }
    }

    private ShareListener mShareListener = new ShareListener() {
        @Override
        public void onShareComplete(String platform) {
            showToast("分享成功");
            EventBus.getDefault().post(new ShareEvent(ShareEvent.success));
        }

        @Override
        public void onShareError(String platform, String errorInfo) {
            Logger.e("分享失败, " + errorInfo);
            showToast("分享失败");
            EventBus.getDefault().post(new ShareEvent(ShareEvent.error));
        }

        @Override
        public void onShareCancel(String platform) {
            showToast("取消分享");
        }
    };

}
